package com.iretailer.report.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iretailer.report.dto.PageResult;
import com.iretailer.report.dto.QueryOption;
import com.iretailer.report.mapper.CategoriesMapper;
import com.iretailer.report.model.Categories;
import com.iretailer.report.util.StringUtil;
import org.apache.commons.collections.map.HashedMap;
import org.quartz.CronExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: xjw
 * @Date: 2019/1/24 11:05
 * @Description:
 */
@Service
public class CategoriesService extends ServiceImpl<CategoriesMapper, Categories> {

    @Autowired
    private CategoriesMapper categoriesMapper;

    /**
     * 根据 keyName 查询出
     */
    @Cacheable(value = "selectCategoryByKeyName", key = "#keyName")
    public Categories selectCategoryByKeyName(String keyName) {
        return categoriesMapper.selectOne(new QueryWrapper<Categories>().lambda().eq(Categories::getKeyName, keyName));
    }

    /**
     * 根据 keyNames 查询出
     */
    public List<Categories> selectCategoryByKeyNames(List<String> keyName) {
        return categoriesMapper.selectList(new QueryWrapper<Categories>().lambda().in(Categories::getKeyName, keyName));
    }

    /**
     * 根据父 id 查询 category 并分页
     *
     * @param parentId
     * @param queryOption
     * @return
     */
    public PageResult<Categories> selectByParentIdPage(String parentId, QueryOption queryOption) {
        Page page = new Page<Categories>(1, Long.MAX_VALUE);
        QueryWrapper<Categories> queryWrapper = new QueryWrapper<>();
        if (parentId != null) {
            queryWrapper.eq("parentId", parentId);
        }
        queryOption.judge(page, queryWrapper);
        queryWrapper.orderByAsc("Ranked");
        categoriesMapper.selectPage(page, queryWrapper);
        return new PageResult<>(page.getTotal(), page.getRecords());
    }

    /**
     * 根据 parenId 查询
     */
    public List<Categories> selectCategoryByParentId(String parentId) {
        return categoriesMapper.selectCategoryByParentId(parentId);
    }

    /**
     * 根据 keyName 查询出 其子categories
     */
    public List<Categories> findChildrenCategoriesByKeyName(String keyName) {
        Categories category = selectCategoryByKeyName(keyName);
        if (category != null) {
            return selectCategoryByParentId(category.getId());
        } else {
            return new ArrayList<>();
        }
    }

    @Cacheable(value = "getAgeTypeMap")
    public Map<String, Categories> getAgeTypeMap() {
        List<Categories> ageTypes = findChildrenCategoriesByKeyName("AgeType");
        Map<String, Categories> ageTypeMap = ageTypes.stream().collect(Collectors.toMap(Categories::getKeyName, a -> a));
        return ageTypeMap;
    }

    /**
     * 树形结构
     */
    public List<Categories> convertTree(List<Categories> categories, String parentId) {
        List<Categories> result = new ArrayList<>();
        categories.forEach(it -> {
            if (it.getParentId() != null && (it.getParentId()).equals(parentId)) {
                List<Categories> children = convertTree(categories, it.getId());
                it.setChildren(children);
                result.add(it);
            }
        });
        return result;
    }

    @CacheEvict(value = {"selectCategoryByKeyName", "getAgeTypeMap"}, allEntries = true)
    public boolean deleteByIds(List<String> ids) {
        if (ids != null && ids.size() > 0) {
            //先判断是否有子节点
            for (String id : ids) {
                List<Categories> childrens = list(new QueryWrapper<Categories>().lambda().eq(Categories::getParentId, id));
                if (childrens != null && childrens.size() > 0) {
                    return false;
                }
            }
            //如果没有子节点就进行删除
            return removeByIds(ids);
        } else {
            return false;
        }
    }

    /**
     * 添加或者更新
     */
    @CacheEvict(value = {"selectCategoryByKeyName", "getAgeTypeMap"}, allEntries = true)
    public boolean saveOrUpdate(Categories categories, String userName) {

        categories.setUpdateTime(LocalDateTime.now());
        categories.setUpdateUser(userName);

        if (StringUtil.notEmpty(categories.getId())) {
            categoriesMapper.updateById(categories);
            return true;
        } else {
            categoriesMapper.insert(categories);
            return true;
        }
    }


}
